using System;
using System.Collections.Generic;
using System.Linq;

using Castle.Core;

namespace Brilliance
{
    public class ActiveViewsDictionary
    {
        private readonly IDictionary<Type, IView> activeViews;

        public ActiveViewsDictionary()
        {
            activeViews = new Dictionary<Type, IView>();
        }

        public void Add(Type type, IView view)
        {
            view.Disposed += view_Disposed;
            activeViews.Add(type, view);
        }

        private void view_Disposed(object sender, EventArgs e)
        {
            IView view;
            if (TryGetValue(sender.GetType(), out view))
            {
                activeViews.Remove(sender.GetType());
            }
        }

        public bool TryGetValue(Type key, out IView value)
        {
            return activeViews.TryGetValue(key, out value);
        }

        public void CloseAllExceptView(Type dontCloseThisTypeOfView)
        {
            var viewsToClose = activeViews.Values.Where((x=>!x.GetType().Equals(dontCloseThisTypeOfView))).ToList();

            viewsToClose.ForEach(x=>x.CloseView());
        }
    }

}